package com.yy.finvideoplayer.utils

import android.content.Context
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.io.FileNotFoundException
import java.io.IOException
import java.io.InputStream

/**
 * @Description: JsonUtil
 * @Author: yiw89
 * @CreateDate: 2025/9/14 14:47
 * @Version: 1.0
 */
object JsonUtil {

    // 新增：从assets读取JSON文件内容为字符串
    fun readJsonFileFromAssets(context: Context, fileName: String): String {
        return try {
            context.assets.open(fileName).bufferedReader().use { it.readText() }
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
            "{}" // 文件不存在时返回空对象
        } catch (e: IOException) {
            e.printStackTrace()
            "{}" // IO异常时返回空对象
        } catch (e: Exception) {
            e.printStackTrace()
            "{}" // 其他异常时返回空对象
        }
    }

    inline fun <reified T> loadFromAssets(context: Context, fileName: String): T? {
        return try {
            val inputStream: InputStream = context.assets.open(fileName)
            val jsonString = inputStream.bufferedReader().use { it.readText() }
            val gson = Gson()
            val type = object : TypeToken<T>() {}.type
            gson.fromJson(jsonString, type)
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    // 专门处理列表的重载方法
    inline fun <reified T> loadListFromAssets(context: Context, fileName: String): List<T> {
        return loadFromAssets<List<T>>(context, fileName) ?: emptyList()
    }

    //对象转JSON字符串
    fun toJson(obj: Any?): String {
        return if (obj == null) {
            "null"
        } else {
            try {
                val gson = Gson()
                gson.toJson(obj)
            } catch (e: Exception) {
                e.printStackTrace()
                "null"
            }
        }
    }

    // 新增：解析JSON字符串到Map
    fun jsonToMap(jsonString: String?): Map<String, Any?> {
        if (jsonString.isNullOrBlank()) {
            return emptyMap()
        }

        return try {
            val gson = Gson()
            val type = object : TypeToken<Map<String, Any?>>() {}.type
            gson.fromJson(jsonString, type) ?: emptyMap()
        } catch (e: Exception) {
            e.printStackTrace()
            emptyMap()
        }
    }



}